package filter

import (
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"library/Vo"
	"library/common"
	"library/config"
	"library/model"
	"library/utils"
	"net/http"
	"strings"
)

func AuthenticationFilter() gin.HandlerFunc {
	// 权限认证
	return func (ctx *gin.Context) {
		tokenString := ctx.GetHeader("Authorization")

		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"code" : common.StatusPermissionDeny,
				"message" : "权限不足",
			})
			ctx.Abort() // 禁止接下来的Handler的执行
			return
		}

		tokenString = tokenString[7:]
		token, claims, err := utils.ParseToken(tokenString)
		if err != nil || !token.Valid{
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"code" : common.StatusPermissionDeny,
				"message" : "权限不足",
			})
			ctx.Abort() // 禁止接下来的Handler的执行
			return
		}

		//验证通过，获取userId
		userId := claims.UserId
		db := config.GetDB()
		var user model.User
		err = db.First(&user, userId).Error
		if errors.Is(err, gorm.ErrRecordNotFound) {
			//根据userId没有找到用户
			Vo.ResponseFiled(ctx,common.StatusPermissionDeny, "权限不足")
			ctx.Abort()
			return
		}

		//将user写入上下文
		ctx.Set("user", user)
		ctx.Next()
	}
}

